<?php

function Buildings($bot)
{
   if($bot->firstrun)
   {
      //not work if it's first bot cycle
		$Name = "buildings"; $Version = "1.8"; $Date = "29.10.2011";
		$bot->ld->UpdatePluginVersion($bot, $Name, $Version, $Date )  ;
		return;
   }

   //getting plugin configurations
   $data = $bot->ld->GetPlSettings("buildings");
   if( ! isset($data))
      return;

   $msg = $bot->irc('u') . $bot->irc('b');
   $msg .= $bot->irc('cc') . '2';
   $msg .= $bot->irc('ff') . '13,5' . chr(232) . $bot->irc('ff') . '14,5';
   $msg .= 'Starting Plugin: BUILDINGS';
   $bot->SendMsg($msg);

   //$bot->ReloadConfig(); //initial stats
	if ($bot->currentWorld != "world_main") $bot->LoadWorldObjects("world_main");

   //==========================================================================
   $yesterday = time() - 86400;

   if(isset($data->AcceptDayBonus))
   {
      if($data->AcceptDayBonus == "1")
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Daily] Accept daily bonus is ON');
         if($yesterday > $bot->previousBonusTime)
         {
            $bot->SendMsg('[BUILDINGS-Daily] Accepting daily bonus now');
            $bot->AcceptBonus();
            if(isset($bot->error_msg))              {$bot->ReloadConfig();}
         }
      }
   }
   //========================================================================== - by tonycell
   $todo = array();
   $Objects = $bot->ld->GetObjects();
   $i = 0;
   foreach($Objects as $obj1)
   {
      if($obj1['className'] == "ZooEnclosure")
      {
         $zoo_sid = "zoo_" . $i;
         $zoo_sID = "zoo_" . $i . "ID";
         if(isset($data->$zoo_sid) && ($data->$zoo_sid))
         {
            $todo[] = $bot->ld->GetObjectById($data->$zoo_sID);
         }
         $i++;
      }
   }
   if(count($todo) > 0)
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Zoo] Action started...');
         foreach($todo as $key=>$obj)
         {
            if($obj["state"] == "grown")
            {
               $bot->SendMsg('[BUILDINGS-Zoo] Collecting from ' . $obj['itemName']);
               $bot->ObjectAction($obj, "harvest", "Zoo");
               if(isset($bot->error_msg))
                  $bot->ReloadConfig();
            }
            else
            {
               $bot->SendMsg('[BUILDINGS-Zoo] ' . $obj['itemName'] . ' is not ready for collecting');
            }
         }
         $bot->SendMsg('[BUILDINGS-Zoo] Action done.');
      }
   //========================================================================== - by Tonycell
   $todo = array();
   $Objects = $bot->ld->GetObjects();
   $i = 0;
   foreach($Objects as $obj1)
   {
      if($obj1['className'] == "PowerStation")
      {
         $powersid = "power" . $i;
         $powersID = "power" . $i . "ID";
         if(isset($data->$powersid) && ($data->$powersid))
         {
            $todo[] = $bot->ld->GetObjectById($data->$powersID);
         }
         $i++;
      }
   }
   if(count($todo) > 0)
      {
         $bot->SendMsg('[BUILDINGS-PowerStation] Action started...');
         foreach($todo as $key=>$obj)
         {
            if(($obj["className"] == "PowerStation") && ((int)$obj['mechanicData']['streakData']['inactiveTime'] > -1))
            {
            $bot->SendMsg('[BUILDINGS-PowerStation] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') : Supplying...');
			   $bot->NewObjectAction($obj, "streakData", "GMPlay", "supply", "Powerstation");
               //$bot->supplyDAM($obj);
               if(isset($bot->error_msg))                 {$bot->ReloadConfig();}
            }
         }
         $bot->SendMsg('[BUILDINGS-PowerStation] Action done.');
      }
   //================== harvest/harvestState ======================================================== - by tonycell   
   $todo = array();
   $Objects = $bot->ld->GetObjects();
   $i = 0;
   foreach($Objects as $obj1)
   {
      if($obj1['className'] == "Mall")
      {
         $mall_sid = "mall_" . $i;
         $mall_sID = "mall_" . $i . "ID";
         if(isset($data->$mall_sid) && ($data->$mall_sid))
         {
            $todo[] = $bot->ld->GetObjectById($data->$mall_sID);
         }
         $i++;
      }
   }
   if(count($todo) > 0)
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Mall] Action started...');
         foreach($todo as $key=>$obj)
         {
            $bot->SendMsg('[BUILDINGS-Mall] ' . $obj['mechanicData']['name'] . ' (' . $obj['itemName'] . ')');
			
            //Visiting
            $bot->SendMsg('[BUILDINGS-Mall] ' . $obj['itemName'] . ': Sending visitors...');
            $bot->processVisits($obj);
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
            //Harvesting
            $bot->SendMsg('[BUILDINGS-Mall] ' . $obj['itemName'] . ': Harvesting...');
            $bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "Mall");
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
            //Supplying
            $bot->SendMsg('[BUILDINGS-Mall] ' . $obj['itemName'] . ': Supplying... (with goods)');
            $bot->NewObjectAction($obj, "supply", "GMPlay", "supply", "Mall");
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
         }
         $bot->SendMsg('[BUILDINGS-Mall] Action done.');
      } 
   //==================== harvest/harvestState ====================================================== - by tonycell 
   if(isset($data->hotel_resort) ||
   isset($data->hotel_sailboat) ||
   isset($data->hotel_tiki) ||
   isset($data->hotel_casino) ||
   isset($data->hotel_terror) ||
   isset($data->hotel_honeymoon))
   {
      $todo = array();
      if(isset($data->hotel_resort) && ($data->hotel_resort))
         $todo[] = $bot->ld->GetObjectById($data->hotel_resortID);
      if(isset($data->hotel_sailboat) && ($data->hotel_sailboat))
         $todo[] = $bot->ld->GetObjectById($data->hotel_sailboatID);
      if(isset($data->hotel_terror) && ($data->hotel_terror))
         $todo[] = $bot->ld->GetObjectById($data->hotel_terrorID);
      if(isset($data->hotel_tiki) && ($data->hotel_tiki))
         $todo[] = $bot->ld->GetObjectById($data->hotel_tikiID);
      if(isset($data->hotel_casino) && ($data->hotel_casino))
         $todo[] = $bot->ld->GetObjectById($data->hotel_casinoID);
	  if(isset($data->hotel_honeymoon) && ($data->hotel_honeymoon))
         $todo[] = $bot->ld->GetObjectById($data->hotel_honeymoonID);

      if(count($todo) > 0)
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Hotel] Action started...');
         foreach($todo as $key=>$obj)
         {
            $bot->SendMsg('[BUILDINGS-Hotel] ' . $obj['mechanicData']['name'] . ' (' . $obj['itemName'] . ')');
            //Visiting
            $bot->SendMsg('[BUILDINGS-Hotel] ' . $obj['itemName'] . ': Sending visitors...');
            $bot->processVisits($obj);
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
            //Harvesting
            $bot->SendMsg('[BUILDINGS-Hotel] ' . $obj['itemName'] . ': Harvesting...');
            $bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "Hotel");
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
            //Supplying
            $bot->SendMsg('[BUILDINGS-Hotel] ' . $obj['itemName'] . ': Supplying... (with goods)');
            $bot->NewObjectAction($obj, "supply", "GMPlay", "supply", "Hotel");
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
         }
         $bot->SendMsg('[BUILDINGS-Hotel] Action done.');
      }
   }
   //==================== harvest/harvestState ======================================================
   if(isset($data->theme_park))
   {
      $todo = array();
      if(isset($data->theme_park) && ($data->theme_park))
         $todo[] = $bot->ld->GetObjectById($data->theme_parkID);

      if(count($todo) > 0)
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Park] Action started...');
         foreach($todo as $key=>$obj)
         {

            //$bot->SendMsg('[BUILDINGS-Hotel] ' . $obj['mechanicData']['name'] . ' (' . $obj['itemName'] . ')');
            //Visiting
            $bot->SendMsg('[BUILDINGS-Park] ' . $obj['itemName'] . ': Sending visitors...');
            $bot->processVisits($obj);
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
            //Harvesting
            $bot->SendMsg('[BUILDINGS-Park] ' . $obj['itemName'] . ': Harvesting...');
            $bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "Park");
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
            //Supplying
            $bot->SendMsg('[BUILDINGS-Park] ' . $obj['itemName'] . ': Supplying... (with goods)');
            $bot->NewObjectAction($obj, "supply", "GMPlay", "supply", "Park");
            if(isset($bot->error_msg))
               $bot->ReloadConfig();//Error checking
         }
         $bot->SendMsg('[BUILDINGS-Park] Action done.');
      }
   }
   //============================================================================
   // Residences
   //============================================================================
   if(isset($data->collectrent))
   {
      if($data->collectrent == "1")
      {
         $reload = 0;

         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Residences] Action started...');
         if(count($data->collectRentIN) == 0)
            $bot->SendMsg('[BUILDINGS-Residences] You need to select at least one building to collect.');

         if(($bot->energy <= 0) && ($data->echeck == "1"))
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            foreach ($data->collectRentIN as $id) //collect in rounds
            {
              $obj = $bot->fobjects["w$id"];
              $popdiff = $bot->xmlsOb->GetResidencesMaxPopulation($obj["itemName"]) - $obj["currentPopulation"];
              if (($obj["className"] == "Residence") &&
                  ($obj["state"] == "grown") &&
                  ($popdiff > 0 || $data->rentvacant != 1) &&
                  ($obj["isConnectedToRoad"]))
              {
                $bot->SendMsg('[BUILDINGS-Residences] '.$obj["itemName"]." ($id) : ".$obj["currentPopulation"]."0 / ".$bot->xmlsOb->GetResidencesMaxPopulation($obj["itemName"]).'0');
                $bot->ObjectAction($obj, "harvest", "Residence");


                if (isset($bot->error_msg))
                {
                  $bot->ReloadConfig();
                  if ($data->echeck=="1") $hasenergy = $bot->CheckEnergy();
                  else $hasenergy = 0;
                  if (($hasenergy == 0) && ($bot->Energy == 0)) { break; }
                }
                else
                {
                  $reload++;
                  //check for streakbonus
                  if(isset($data->Rbonus)&&($data->Rbonus=="1")) $bot->streakBonus3();
                }
              }
            }
         }
         else
         {
            $bot->SendMsg('[BUILDINGS-Residences] No energy to collect.');
         }
         $bot->SendMsg('[BUILDINGS-Residences] Action done.');

         //trying to capture queued Doggies ($reload > 1) &&
         if(($reload > 0) && (isset($data->doggie) && $data->doggie))
         {  
            $bot->SendMsg('=====================================');
            $bot->SendMsg('[BUILDINGS-Doggies] Action started...');
            if(isset($bot->dogQueue) && (is_array($bot->dogQueue)))
            {
               foreach($bot->dogQueue as $keybandit=>$bandit)
               {
                  if($bot->Try2CaptureOneDoggie($bandit) === true)
                  {
                     if(isset($bot->error_msg)) {$bot->ReloadConfig();$reload = 0;}
                  }
               }
            }
            $bot->SendMsg('[BUILDINGS-Doggies] Action done.');
			$bot->ReloadConfig();$reload = 0;
         }
         if($reload > 0)  $bot->fobjects = $bot->LoadWorldObjects("world_main");
      }
   }
   //==========================================================================
   // CustomResidence
   //================ harvest / harvestEndTS ==========================================================
   $todo = array();
   $Objects = $bot->ld->GetObjects();
   $i = 0;
   foreach($Objects as $obj1)
   {
      if($obj1['className'] == "CustomResidence")
      {
         $collectCustomResidencesid = "collectCustomResidence" . $i;
         $collectCustomResidencesID = "collectCustomResidence" . $i . "ID";
         if(isset($data->$collectCustomResidencesid) && ($data->$collectCustomResidencesid))
         {
            $todo[] = $bot->ld->GetObjectById($data->$collectCustomResidencesID);
         }
         $i++;
      }
   }
   if(count($todo) > 0)
   {
      $bot->SendMsg('=====================================');
      $bot->SendMsg('[BUILDINGS-Residences] Action started...');
	  
      foreach($todo as $key=>$obj)
      {
         //energy check
         if(($bot->energy <= 0) && ($data->echeck == "1"))
              $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            $currentpopulation = 0;
            $popmax = 0;		
			$currentpopulation = $obj['currentPopulation'];
			$popmax = $bot->xmlsOb->GetResidencesMaxPopulation($obj['itemName']);
			if (is_array($obj['mechanicData']['slots']))
			{
				foreach($obj['mechanicData']['slots'] as $j=>$floor)
				{
					if (!empty($floor))
					{
						$popmax += $bot->xmlsOb->GetResidencesMaxPopulation($floor);
					}
				}
			}
			$currentpopulation = $currentpopulation * 10;
            $popmax = $popmax * 10;

            if (($obj["state"] == "grown") &&
			   ($currentpopulation < $popmax || $data->rentvacant != 1) &&
               ($obj["isConnectedToRoad"]))
            {
               $bot->SendMsg('[BUILDINGS-Residences] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') [' . $currentpopulation . '/' . $popmax . '] : Collecting...');
			   //$bot->collectRent($obj);
			   $bot->ObjectAction($obj, "harvest", "CustomResidence");
              //$bot->NewObjectAction1($obj, "harvest");
               if(isset($bot->error_msg))
               {
                  $bot->ReloadConfig();
                  if($data->echeck == "1")
                     $hasenergy = $bot->CheckEnergy();
                  else
                     $hasenergy = 0;
                  if(($hasenergy == 0) && ($bot->Energy == 0))                    {break;}
               }
               else
               {
                  $reload++;
                  //check for streakbonus
                  if(isset($data->Rbonus) && ($data->Rbonus == "1"))
                     $bot->streakBonus3();
               }

            }
            else              {$bot->SendMsg('[BUILDINGS-Residences] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') is not ready to harvest (missing energy, no vacant or not connected to road )...');}

         }//energy check
      }

      $bot->SendMsg('[BUILDINGS-Residences] Action done.');
        }
   
   //==========================================================================
   // Skyscraper
   //================ harvest / harvestEndTS ==========================================================
   $todo = array();
   $Objects = $bot->ld->GetObjects();
   $i = 0;
   foreach($Objects as $obj1)
   {
      if($obj1['className'] == "Skyscraper")
      {
         $collectskysid = "collectsky" . $i;
         $collectskysID = "collectsky" . $i . "ID";
         if(isset($data->$collectskysid) && ($data->$collectskysid))
         {
            $todo[] = $bot->ld->GetObjectById($data->$collectskysID);
         }
         $i++;
      }
   }
   if(count($todo) > 0)
   {
      $bot->SendMsg('=====================================');
      $bot->SendMsg('[BUILDINGS-Skyscraper] Action started...');
	  
      foreach($todo as $key=>$obj)
      {
         //energy check
         if(($bot->energy <= 0) && ($data->echeck == "1"))
              $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {

            $popmax = 0;
            $currentpopulation = 0;
            $popmax += (int)$bot->xmlsOb->GetResidencesMaxPopulation($obj["itemName"]);
            $currentpopulation += $obj["currentPopulation"];
            $currentpopulation = $currentpopulation * 10;
            $popmax = $popmax * 10;
			$bot->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
            if((($currentpopulation < $popmax || $data->rentvacant != 1))&& ($clientEnqueueTime >= $obj["mechanicData"]["harvestEndTS"]))
            // &&($obj["isConnectedToRoad"]))
            {
               $bot->SendMsg('[BUILDINGS-Skyscraper] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') : Harvesting...');
               $bot->SendMsg('[BUILDINGS-Skyscraper] ' . '[Population: ' . $currentpopulation . '/' . $popmax . ']');
               $bot->NewObjectAction($obj, "harvestEndTS", "GMPlay", "harvest", "Skyscraper");
               if(isset($bot->error_msg))
               {
                  $bot->ReloadConfig();
                  if($data->echeck == "1")
                     $hasenergy = $bot->CheckEnergy();
                  else
                     $hasenergy = 0;
                  if(($hasenergy == 0) && ($bot->Energy == 0))                    {break;}
               }
               else
               {
                  $reload++;
                  //check for streakbonus
                  if(isset($data->Rbonus) && ($data->Rbonus == "1"))
                     $bot->streakBonus3();
               }

            }
            else              {$bot->SendMsg('[BUILDINGS-Skyscraper] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') is not ready to harvest (missing energy, no vacant or not connected to road )...');}

         }//energy check
      }

      $bot->SendMsg('[BUILDINGS-Skyscraper] Action done.');
    }  
   //==========================================================================
   // Neighbourhoods - by dada79
   //================ harvest/harvestState ==========================================================
   $todo = array();
   $Objects = $bot->ld->GetObjects();
   $i = 0;
   foreach($Objects as $obj1)
   {
      if($obj1['className'] == "Neighborhood")
      {
         $hoodsid = "hood_" . $i;
         $hoodsID = "hood_" . $i . "ID";
         if(isset($data->$hoodsid) && ($data->$hoodsid))
         {
            $todo[] = $bot->ld->GetObjectById($data->$hoodsID);
         }
         $i++;
      }
   }
   if(count($todo) > 0)
   {
      $bot->SendMsg('=====================================');
      $bot->SendMsg('[BUILDINGS-Neighbourhood] Action started...');

      foreach($todo as $key=>$obj)
      {
         //energy check
         $energyReq = 0;
         $energyReq = count($obj['mechanicData']['harvestState']['resources']);
         if(($bot->energy <= ($energyReq - 1)) && ($data->echeck == "1"))  $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy >= $energyReq)
         {
            $popmax = 0;
            $currentpopulation = 0;
            $stategrown = true;
            foreach((array)$obj['mechanicData']['slots'] as $j=>$house)
            {
               $popmax += (int)$bot->xmlsOb->GetResidencesMaxPopulation($house["itemName"]);
               $currentpopulation += $house["currentPopulation"];
               if($house["state"] == 'grown') {$stategrown &= true;}
               else {$stategrown &= false;}
            }
            $currentpopulation = $currentpopulation * 10;
            $popmax = $popmax * 10;
            if((count($obj['mechanicData']['harvestState']['resources']) <= $bot->energy)
             && (count($obj['mechanicData']['harvestState']['resources']) > 0)
             && ($stategrown)
             && ($currentpopulation < $popmax || $data->rentvacant != 1)
             && ($obj["isConnectedToRoad"]))
            {
               $bot->SendMsg('[BUILDINGS-Neighbourhood] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') : Harvesting...');
               $bot->SendMsg('[BUILDINGS-Neighbourhood] ' . '[Population: ' . $currentpopulation . '/' . $popmax . ']');
               $bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "Neighbourhood");

               //if (isset($bot->error_msg)) { $bot->ReloadConfig(); }
               if(isset($bot->error_msg))
               {
                  $bot->ReloadConfig();
                  if($data->echeck == "1")
                     $hasenergy = $bot->CheckEnergy();
                  else
                     $hasenergy = 0;
                  if(($hasenergy == 0) && ($bot->Energy == 0))                    {break;}
               }
               else
               {
                  $reload++;
                  //check for streakbonus
                  if(isset($data->Rbonus) && ($data->Rbonus == "1"))
                     $bot->streakBonus3();
               }

            }
            else              {$bot->SendMsg('[BUILDINGS-Neighbourhood] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') is not ready to harvest (missing energy, no vacant or not connected to road )...');}

         }//energy check
      }

      $bot->SendMsg('[BUILDINGS-Neighbourhood] Action done.');

      //trying to capture queued Doggies ($reload > 1) &&
      if(($reload > 0) && (isset($data->doggie) && $data->doggie))
      {  
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Doggies] Action started...');
         if(isset($bot->dogQueue) && (is_array($bot->dogQueue)))
         {
            foreach($bot->dogQueue as $keybandit=>$bandit)
            {
               if($bot->Try2CaptureOneDoggie($bandit) === true)
               {
                  if(isset($bot->error_msg)) {$bot->ReloadConfig();$reload = 0;}
               }
            }
         }
         $bot->SendMsg('[BUILDINGS-Doggies] Action done.');
		 $bot->ReloadConfig();$reload = 0;
      }
      if($reload > 0)   $bot->fobjects = $bot->LoadWorldObjects("world_main");
   }
   //============================================================================
   // BUSINESS
   //============================================================================
   $repeattimes = 1;
   if((isset($data->rcollect) && ($data->rcollect == "1")) && (isset($data->rtimes) && ($data->rtimes > 0)))
   {
      $repeattimes = $data->rtimes;
   }

   //added LOOP for repeated collecting
   for($times = 1; $times <= $repeattimes; $times++)
   {
      if($repeattimes > 1)
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Business] LOOP #' . $times . ' starting...');
      }
    //===============================VISTING BUSINESS BUILDINGS SELECTED===========================================
      if(isset($data->process) && isset($data->supplybbplus))
      {
         if(($data->process == "1") && ($data->supplybbplus == "1"))
         {
            $reload = 0;
            $bot->SendMsg('=====================================');
            $bot->SendMsg('[BUILDINGS-Business] Visiting business buildings (before supply)');

            //foreach ($bot->fobjects as $obj)
            foreach($data->collectbbIN as $id)
            {
               $obj = $bot->fobjects["w$id"];
               //if (($obj["className"] == "Business") && ($obj["state"] == "open") && in_array($obj["itemName"], $data->collectbbIN))
               if($obj["state"] == "open")
               {
                  $bot->processVisits($obj);
                  $reload++;
               }
               if(isset($bot->error_msg)) {$bot->ReloadConfig();$reload = 0;}
            }
            if($times > 1)
               sleep(1);//give some time to the server can update the database
            $bot->SendMsg('[BUILDINGS-Business] Visiting business buildings done.');
            if($reload > 0) $bot->fobjects = $bot->LoadWorldObjects("world_main");
         }
      }
      //===============================VISTING ALL BUSINESS BUILDINGS===========================================
      if(isset($data->process) && isset($data->supplybbplusall))
      {
         if(($data->process == "1") && ($data->supplybbplusall == "1"))
         {
            $reload = 0;
            $bot->SendMsg('=====================================');
            $bot->SendMsg('[BUILDINGS-Business] Visiting all business buildings (before supply)');

            foreach($bot->fobjects as $obj)
            {
               if(($obj["className"] == "Business") && ($obj["state"] == "open"))
               {
                  $bot->processVisits($obj);
                  $reload++;
               }
               if(isset($bot->error_msg))                 {$bot->ReloadConfig();$reload = 0;}
            }
            if($times > 1) sleep(1);//give some time to the server can update the database
            $bot->SendMsg('[BUILDINGS-Business] Visiting all business buildings done.');
            if($reload > 0) $bot->fobjects = $bot->LoadWorldObjects("world_main");
         }
      }
      //===============================COLLECT BUSINESS BUILDINGS SELECTED===========================================
      if(isset($data->collect) && isset($data->collectbb))
      {
         if(($data->collect == "1") && ($data->collectbb == "1"))
         {
            $reload = 0;
            $bot->SendMsg('=====================================');
            $bot->SendMsg('[BUILDINGS-Business] Action started...');
            //$bot->ReloadConfig();

            if(count($data->collectbbIN) == 0)
               $bot->SendMsg(' *** You did not select any business in buildings.');

            if(($bot->energy <= 0) && ($data->echeck == "1"))
               $bot->CheckEnergy();//Check if has energy on iventory;
            if($bot->energy > 0)
            {
               foreach($data->collectbbIN as $id)
               {
                  $obj = $bot->fobjects["w$id"];
                  if($obj["state"] == "closedHarvestable")
                  {
                     $bot->actionBusiness("harvest", $obj, "closed", (int)$obj['lastSavedMax'], "Business");
                     $reload++;

                     if(isset($bot->error_msg))
                     {
                        $bot->ReloadConfig();$reload = 0;
                        if($data->echeck == "1")
                           $hasenergy = $bot->CheckEnergy();
                        else
                           $hasenergy = 0;
                        if(($hasenergy == 0) && ($bot->Energy == 0))                          {break;}
                     }
                     else
                        //check for streakbonus
                        if(isset($data->Bbonus) && ($data->Bbonus == "1")) $bot->streakBonus3();
                  }
               }
            }
            else
            {
               $bot->SendMsg('[BUILDINGS-Business] No energy to collect.');
            }
            $bot->SendMsg('[BUILDINGS-Business] Action done.');

            //trying to capture queued bandits ($reload > 1) &&
            if(($reload > 0) && (isset($data->bandit) && $data->bandit))
            {  
               $bot->SendMsg('=====================================');
               $bot->SendMsg('[BUILDINGS-Bandits] Action started...');
               if(isset($bot->arBanditQueue) && (is_array($bot->arBanditQueue)))
               {
                  foreach($bot->arBanditQueue as $keybandit=>$bandit)
                  {
                     if($bot->Try2CaptureOneBandit($bandit) === true)
                     {
                        if(isset($bot->error_msg)) { $bot->ReloadConfig();$reload = 0; }
                     }
                  }
               }
               $bot->SendMsg('[BUILDINGS-Bandits] Action done.');
			   $bot->ReloadConfig();$reload = 0;
            }
            if($reload > 0)   $bot->fobjects = $bot->LoadWorldObjects("world_main");
         }
      }
      //===============================COLLECT ALL BUSINESS BUILDINGS===========================================
      if(isset($data->collect) && isset($data->collectbball))
      {
         if(($data->collect == "1") && ($data->collectbball == "1"))
         {
            $reload = 0;
            $bot->SendMsg('=====================================');
            $bot->SendMsg('[BUILDINGS-Business] Action started...');
            //$bot->ReloadConfig();

            if(($bot->energy <= 0) && ($data->echeck == "1"))
               $bot->CheckEnergy();//Check if has energy on iventory;
            if($bot->energy > 0)
            {
               foreach($bot->fobjects as $obj)
               {
                  // 2011-02-08 added check if business is in the collect list.
                  if(($obj["className"] == "Business") && ($obj["state"] == "closedHarvestable"))
                  {
                     $bot->actionBusiness("harvest", $obj, "closed", (int)$obj['lastSavedMax'], "Business");
                     $reload++;

                     if(isset($bot->error_msg))
                     {
                        $bot->ReloadConfig();$reload = 0;
                        if($data->echeck == "1")
                           $hasenergy = $bot->CheckEnergy();
                        else
                           $hasenergy = 0;
                        if(($hasenergy == 0) && ($bot->Energy == 0))                          {break;}
                     }
                     else
                        //check for streakbonus
                        if(isset($data->Bbonus) && ($data->Bbonus == "1"))
                           $bot->streakBonus3();
                  }
               }
            }
            else
            {
               $bot->SendMsg('[BUILDINGS-Business] No energy to collect.');
            }
            $bot->SendMsg('[BUILDINGS-Business] Action done.');

            if(($reload > 0) && (isset($data->bandit) && $data->bandit))
            {  
               //trying to capture queued bandits ($reload > 1) &&
               $bot->SendMsg('=====================================');
               $bot->SendMsg('[BUILDINGS-Bandits] Action started...');
               if(isset($bot->arBanditQueue) && (is_array($bot->arBanditQueue)))
               {
                  foreach($bot->arBanditQueue as $keybandit=>$bandit)
                  {
                     if($bot->Try2CaptureOneBandit($bandit) === true)
                     {
                        if(isset($bot->error_msg))  { $bot->ReloadConfig();$reload = 0; }
                     }
                  }
               }
               $bot->SendMsg('[BUILDINGS-Bandits] Action done.');
			   $bot->ReloadConfig();$reload = 0;
            }
            if($reload > 0)   $bot->fobjects = $bot->LoadWorldObjects("world_main");
         }
      }
      //==================SUPPLY BUSINESS BUILDINGS SELECTED WITH/WITHOUT GOODS===================================
      //redesigned by Tonycell
//      if((isset($data->supply)) && ((isset($data->supplybb))||(isset($data->supplybbb))))
//      {
//         if($data->supply == "1") //supply on/off
//         {
//           $bot->SendMsg('=====================================');
//            if($data->supplybb == "1") //supply with goods
//            {$bot->SendMsg('[BUILDINGS-Business] Supplying business buildings (with goods)...');}
//            else
//               if($data->supplybbb == "1") //supply without goods
//               {$bot->SendMsg('[BUILDINGS-Business] Supplying business buildings (without goods)...');}

               //if ($reload>0) $bot->ReloadConfig();

               //foreach ($bot->fobjects as $obj)
//            $reload = 0;
//            foreach($data->collectbbIN as $id)
//            {
//               $obj = $bot->fobjects["w$id"];
               //collecting
//               if($obj["state"] == "closed")
//               {
//                  if($data->supplybb == "1")   {$bot->supplyBB($obj);}//supply with goods
//                  else
//                  if($data->supplybbb == "1")  {$bot->supplyBBB($obj);}//supply without goods
//                  $reload++;
                  //visiting
                  //if ((isset($data->process)) && (isset($data->supplybbplus)))
                  //{
                  //  if (($data->process == "1") && ($data->supplybbplus == "1"))
                  //  {
                  //    $bot->processVisits($obj); //visiting
                  //  }
                  //}
//               }
//               if(isset($bot->error_msg))                 {$bot->ReloadConfig();$reload = 0;}
//            }
//            $bot->SendMsg('[BUILDINGS-Business] Supplying done.');
//            if($reload > 0)
//               $bot->ReloadConfig();
//         }
//      }
//	  
//	  if (!empty($bot->arCars) && isset($data->carsCollect) && $data->carsCollect)
//      {
      	//suffle array
//      	$arCarsSuffled = array();
//      	foreach($bot->arCars as $k)
//      	{
//      		for($n=0;$n<$k["num"];$n++)
//      		$arCarsSuffled[] = $k["name"];
//      	}
      	 
//      	shuffle($arCarsSuffled);
      	//get 60% of cars - dont know why all cars fail
//      	$arCarsSuffled = array_slice($arCarsSuffled, 0, 0.6*count($arCarsSuffled));
//      	foreach ($arCarsSuffled as $carName)
//      	{
//      		$carCoins = rand(9, 20);
//      		$carCoins = intval($carCoins) * 10;

//      		$bot->Try2CaptureCar($carName, $carCoins);
//      	}
//      }
      //===============================SUPPLY BUSINESS BUILDINGS SELECTED WITHOUT GOODS===========================================
      //addded by phreaker 15-03-2011
      /*	if ((isset($data->supply)) && (isset($data->supplybbb))) {
      		if (($data->supply == "1") && ($data->supplybbb == "1"))
      {
      $bot->SendMsg('=====================================');
      			$bot->SendMsg('[BUILDINGS-Business] Supplying business buildings (without goods)...');
      		  $bot->ReloadConfig();

      			foreach ($bot->fobjects as $obj) {
      				if (($obj["className"] == "Business") && ($obj["state"] == "closed") && in_array($obj["itemName"], $data->collectbbIN)) {
      					$bot->supplyBBB($obj);
      					if ((isset($data->process)) && (isset($data->supplybbplus))) {
      					   if (($data->process == "1") && ($data->supplybbplus == "1")) {
      						   //$bot->SendMsg('Making business buildings ready (after supply)');
      						   $bot->processVisits($obj);
      						}
      					}
      				}
      				if (isset($bot->error_msg)) {
      					$bot->ReloadConfig();
      					break;
      				}
      			}
      			$bot->SendMsg('[BUILDINGS-Business] Supplying done.');
      		}
      	}
      */
      //===============================SUPPLY ALL BUSINESS BUILDINGS WITH/OUT GOODS===========================================
      if((isset($data->supply)) && ((isset($data->supplybball))||(isset($data->supplybbball))))
      {
         if($data->supply == "1")  //supply on/off
         {
            //$bot->SendMsg('=====================================');
            //$bot->SendMsg('[BUILDINGS-Business] Supplying all business buildings (without goods)...');
            //$bot->ReloadConfig();

            $bot->SendMsg('=====================================');
            if($data->supplybball == "1") //supply with goods
            {$bot->SendMsg('[BUILDINGS-Business] Supplying all business buildings (with goods)...');}
            else
            if($data->supplybbball == "1") //supply without goods
            {$bot->SendMsg('[BUILDINGS-Business] Supplying all business buildings (with premium goods)...');}
          {
            $reload = 0;
            foreach($bot->fobjects as $obj)
            {
               if(($obj["className"] == "Business") && ($obj["state"] == "closed"))
               {
                  if($data->supplybball == "1")  {$bot->actionBusiness("openBusiness", $obj, "closed", "goods", "Business");}//supply with goods
                  else
                  if($data->supplybbball == "1") {$bot->actionBusiness("openBusiness", $obj, "closed", "premium_goods", "Business");}//supply without goods
                  $reload++;
                  if(isset($bot->error_msg)) {$bot->ReloadConfig();$reload = 0;}
               }
            }
            $bot->SendMsg('[BUILDINGS-Business] Supplying done.');
            if($reload > 0) $bot->fobjects = $bot->LoadWorldObjects("world_main");
	      }
		}
	}  
	if (isset($data->carsCollect))
    {
        if($data->carsCollect == "1")
	  {
      	//suffle array
      	$arCarsSuffled = array();
      	foreach($bot->arCars as $k)
      	{
      		for($n=0;$n<$k["num"];$n++)
      		$arCarsSuffled[] = $k["name"];
      	}
		 if ($times > 1) {$bot->ReloadConfig();$bot->SendMsg('[BUILDINGS-Cars] ... still have to wait');}
      	if($times > 1) sleep(83);//give some time to the server can update the database

      	shuffle($arCarsSuffled);
      	//get 60% [21] of cars - dont know why all cars fail
        //$arCarsSuffled = array_slice($arCarsSuffled, 0, 0.6*count($arCarsSuffled));
		//get 50% of cars - dont know why all cars fail
	    $arCarsSuffled = array_slice($arCarsSuffled, 0, 0.5*count($arCarsSuffled));
      	foreach ($arCarsSuffled as $carName)
      	{
      		$carCoins = rand(9, 20);
      		$carCoins = intval($carCoins) * 10;

      		$bot->Try2CaptureCar($carName, $carCoins);
			if($bot->error_msg)break;
		}
	  }
	}	
   //===============================Collect Bridge===========================================	
   if(isset($data->bridgeCollect))
   {
       if($data->bridgeCollect == "1")
       {
         $reload = 0;
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Bridge] Action started...');

         if(($bot->energy <= 0) && ($data->echeck == "1"))
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            foreach($bot->fobjects as $obj)
            {
               if($obj["className"] == "Bridge")
               {
			      $bot->SendMsg('[BUILDINGS-Bridge] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') : Harvesting...');
                  $bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "Bridge");
				        //check for streakbonus
                        if(isset($data->Bbonus) && ($data->Bbonus == "1")) $bot->streakBonus3();
                        $reload++;
               }
               if(isset($bot->error_msg))
               {
                  $bot->ReloadConfig();$reload = 0;
                  if($data->echeck == "1") $hasenergy = $bot->CheckEnergy();
                  else $hasenergy = 0;
                  if(($hasenergy == 0) && ($bot->Energy == 0)) {break 1;}
               }
            }
         }
         else
         {
            $bot->SendMsg('[BUILDINGS-Bridge] No energy to collect the Bridge');
         }
         $bot->SendMsg('[BUILDINGS-Bridge] Action done.');
        }
    }   
   }//END OF COLLECTING LOOP
   
   //===============================TimedBusiness===========================================	
   if(isset($data->actionTimedBusiness))
   {
      if($data->actionTimedBusiness == "1")
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Business] Action started...');

         if($bot->energy <= 0)
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            foreach($bot->fobjects as $obj)
            {
               if($obj["className"] == "TimedBusiness")
               {
                  if($obj["mechanicData"]["harvestState"]["state"] == "supplied")
                  {	//Collect
                     $bot->SendMsg('[BUILDINGS-Business] ' . $obj['itemName'] . ': Harvesting...');
                     $bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "TimedBusiness");					 
					if(isset($data->Bbonus) && ($data->Bbonus == "1"))
                     $bot->streakBonus3();
                  }
				    //Supplying
				     $bot->SendMsg('[BUILDINGS-Business] ' . $obj['itemName'] . ': Supplying... (with goods)');
                     $bot->NewObjectAction($obj, "supplyState", "GMPlay", "supply", "TimedBusiness");
                  if(isset($bot->error_msg))
                  {
                     $bot->ReloadConfig();
                     $hasenergy = $bot->CheckEnergy();
                     if(($hasenergy == 0) && ($bot->Energy == 0))                       {break;}
                  }
               }
            }//foreach
         }
         else
         {
            $bot->SendMsg('[BUILDINGS-Business] No energy to unload the Ships');
         }
         $bot->SendMsg('[BUILDINGS-Business] Action done.');

      }
   }   
    //=================== harvest/harvestState =======================================================	  
   $todo = array();
   $Objects = $bot->ld->GetObjects();
   $i = 0;
   foreach($Objects as $obj1)
   {
      if($obj1['className'] == "MunicipalCenter")
      {
         $MunCentersid = "MunCenter" . $i;
         $MunCentersID = "MunCenter" . $i . "ID";
         if(isset($data->$MunCentersid) && ($data->$MunCentersid))
         {
            $todo[] = $bot->ld->GetObjectById($data->$MunCentersID);
         }
         $i++;
      }
   }
   if(count($todo) > 0)
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-MunCenter] Action started...');
		 
         foreach($todo as $key=>$obj)
         {
            $stategrown = true;
            foreach((array) $obj['mechanicData']['slots'] as $j=>$house)
            {
                if($house["state"] == 'grown')
					$stategrown &= true;
				else
					$stategrown &= false;
            }			
            if ($stategrown)
            {
                //Harvesting
                $bot->SendMsg('[BUILDINGS-MunCenter] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') : Harvesting...');
                $bot->NewObjectAction($obj, "harvestState", "GMPlay", "harvest", "MunicipalCenter");
                if(isset($bot->error_msg))
                {
                  $bot->ReloadConfig();
                }
			    else
                {
                  //check for streakbonus
                  if(isset($data->CCbonus) && ($data->CCbonus == "1"))
                  $bot->streakBonus3();
                }
			   
			}   
            else 
			{
			     $bot->SendMsg('[BUILDINGS-MunCenter] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') is not ready to harvest ...');
		    }   
        }	
        $bot->SendMsg('[BUILDINGS-MunCenter] Action done.');
      }
   //==========================================================================
   if(isset($data->collectLM))
   {
      if($data->collectLM == "1")
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Landmarks] Action started...');
         if(count($data->collectLMIN) == 0)
              $bot->SendMsg('[BUILDINGS-Landmarks] You need to select at least one landmark to collect.');

         if(($bot->energy <= 0) && ($data->echeck == "1"))
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            foreach ($data->collectLMIN as $id) //collect in rounds
            {
              $obj = $bot->fobjects["w$id"];
               if(($obj["className"] == "Landmark") && ($obj["state"] == "grown"))
               {
                  $bot->SendMsg('[BUILDINGS-Landmarks] '.$obj["itemName"]." ($id) ");
                  $bot->collectCommun($obj, "harvest", "Landmark");
                  if(isset($bot->error_msg))
                  {
                     $bot->ReloadConfig();$reload = 0;
                     if($data->echeck == "1")
                        $hasenergy = $bot->CheckEnergy();
                     else
                        $hasenergy = 0;
                     if(($hasenergy == 0) && ($bot->Energy == 0))                    {break;}
                  }
				else
				{
					//check for streakbonus
					if(isset($data->CCbonus) && ($data->CCbonus == "1"))
						$bot->streakBonus3();
				}
               }
            }
         }
         else
         {
            $bot->SendMsg('[BUILDINGS-Landmarks] No energy to collect.');
         }
         $bot->SendMsg('[BUILDINGS-Landmarks] Action done.');
      }
   }
   //==========================================================================
   if(isset($data->collectMu))
   {
      if($data->collectMu == "1")
      {
         $reload = 0;
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Community] Action started...');
         if(count($data->collectMuIN) == 0)
              $bot->SendMsg('[BUILDINGS-Community] You need to select at least one community building to collect.');

         if(($bot->energy <= 0) && ($data->echeck == "1"))
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            foreach ($data->collectMuIN as $id) //collect in rounds
            {
              $obj = $bot->fobjects["w$id"];
               if((($obj["className"] == "Municipal") || ($obj["className"] == "University"))
			   && ($obj["state"] == "grown"))
               {
                  $bot->SendMsg('[BUILDINGS-Community] '.$obj["itemName"]." ($id) ");
                  $bot->collectCommun($obj, "harvest", "Community");
                  $reload++;
                  if(isset($bot->error_msg))
                  {
                     $bot->ReloadConfig();$reload = 0;
                     if($data->echeck == "1") $hasenergy = $bot->CheckEnergy();
                     else $hasenergy = 0;
                     if(($hasenergy == 0) && ($bot->Energy == 0)) {break 1;}
                  }
				else
				{
					$reload++;
					//check for streakbonus
					if(isset($data->CCbonus) && ($data->CCbonus == "1"))
						$bot->streakBonus3();
				}
               }
            }
         }
         else
         {
            $bot->SendMsg('[BUILDINGS-Community] No energy to collect.');
         }
         $bot->SendMsg('[BUILDINGS-Community] Action done.');
      }
   }
   //==========================================================================
   if(isset($data->ClearWildernes))
   {
      if($data->ClearWildernes == "1")
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Trees] Action started...');

         if(($bot->energy <= 0) && ($data->echeck == "1"))
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            foreach($bot->fobjects as $obj)
            {
               if($obj["className"] == "Wilderness")
               {
                  $bot->ObjectAction($obj, "clear", "Wilderness");
                  $reload++;
               }
               //		f (isset($bot->error_msg)) { $bot->ReloadConfig();  break; }
               if(isset($bot->error_msg))
               {
                  $bot->ReloadConfig();
                  if($data->echeck == "1") $hasenergy = $bot->CheckEnergy();
                  else $hasenergy = 0;
                  if(($hasenergy == 0) && ($bot->Energy == 0)) {break 1;}
               }
            }
         }
         else
         {
            $bot->SendMsg('[BUILDINGS-Trees] No energy to chop the Trees');
         }
         $bot->SendMsg('[BUILDINGS-Trees] Action done.');
      }
   }
    //==========================================================================
   if(isset($data->collectSleigh))
   {
      if($data->collectSleigh == "1")
      {
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[BUILDINGS-Sleigh] Action started...');

         if(($bot->energy <= 0) && ($data->echeck == "1"))
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
            foreach($bot->fobjects as $obj)
            {
			   $bot->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
               if(($obj["itemName"] == "deco_santasleigh")&& ($clientEnqueueTime >= $obj["mechanicData"]["endTS"]))
               {
			      $bot->SendMsg('[BUILDINGS-Sleigh] ' . $obj['itemName'] . ' (id: ' . $obj['id'] . ') : Harvesting...');
                  $bot->NewObjectAction($obj, "endTS", "GMPlay", "harvest", "Sleigh");
               }
               if(isset($bot->error_msg))
               {
                  $bot->ReloadConfig();
                  if($data->echeck == "1") $hasenergy = $bot->CheckEnergy();
                  else $hasenergy = 0;
                  if(($hasenergy == 0) && ($bot->Energy == 0)) {break 1;}
               }
            }
         }
         else
         {
            $bot->SendMsg('[BUILDINGS-Sleigh] No energy to collect the Sleigh');
         }
         $bot->SendMsg('[BUILDINGS-Sleigh] Action done.');
      }
   }
   //==========================================================================   
   
}
$this->AddHook('start_buildings', 'Buildings');
?>